package com.blue.common.config;

import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class ThreadPoolConfig {

    //通用线程池
    @Bean(name = "customExecutor")
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); // 核心线程数
        executor.setMaxPoolSize(20); // 最大线程数
        executor.setQueueCapacity(500); // 队列大小
        executor.setKeepAliveSeconds(60); // 线程空闲时间
        executor.setThreadNamePrefix("CustomExecutor-"); // 线程名前缀
        executor.setTaskDecorator(new TaskDecorator() {
            @Override
            public Runnable decorate(Runnable runnable) {
                Map<String, String> map = MDC.getCopyOfContextMap();
                return () -> {
                    try {
                        MDC.setContextMap(map);
                        runnable.run();
                    } finally {
                        MDC.clear();
                    }
                };
            }
        });//使异步线程池获得主线程的上下文
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
        executor.initialize();
        return executor;
    }
}
